import { ProTable } from '@ant-design/pro-components';
import { Button, Popconfirm, message, Modal, Tag, Switch  } from 'antd';
import ScheduleEditorDrawer from "@/pages/schedule/parts/ScheduleEditorDrawer"
import { useRef, useState } from "react";
import { firstValueFrom, map } from "rxjs"
import $http from "@/services/http.service.v2";
import $helper from "@/services/helper.service";
import $wss from '@/services/wss.service';


export default function SchedulePage() {
  const destroyingRef = useRef(false)
  const drawerRef = useRef()
  const actionRef = useRef()
  const listDataRef = useRef([])
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '任务名',
      dataIndex: 'schedule_name',
      render: (_, recode) => {
        return (
          <>
            {recode.schedule_name}[{recode.start_time}]
          </>
        )
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) => {
        return (
          <>
            <Switch loading={stateLoadingItems.includes(record.id)} checked={_ === 1} onChange={checked => onStateChange(checked, record)}/>
          </>
        )
      },
    },
    {
      title: <>操作 <Button onClick={onRefreshAllState} className='ml-1' size='small' type='primary'>更新全部</Button></>,
      key: 'option',
      render: (_, record) => (
        <div className="-mx-1">
          <a className="mx-1" onClick={() => {
            drawerRef.current.open(record)
          }}>编辑</a>
          <Popconfirm
            disabled={destroyingRef.current}
            title="删除任务？"
            description="删除后无法恢复！！"
            okText="删除"
            cancelText="取消"
            onConfirm={() => {
              const loadingKey = $helper.uuid() 
              message.loading({ content: '正在删除...', duration: 0, key: loadingKey })
              destroyingRef.current = true
              $http.deleteSchedule(record.id).subscribe(() => {
                destroyingRef.current = false
                message.destroy(loadingKey)
                actionRef.current?.reload()
              })
          }}
          >
            <a className="mx-1 text-red-600">删除</a>
          </Popconfirm>
          <Button size='small' type="primary" className="mx-1" onClick={() => {
            $wss.hotRefreshSchedule([record.id])
          }}>更新</Button>
        </div>
      ),
    },
  ];
  const [stateLoadingItems, setStateLoadingItems] = useState([])
  function onStateChange(checked, record) {
    setStateLoadingItems([...stateLoadingItems, record.id])
    $http.updateSchedule({id: record.id, status: checked ? 1 : 2 }).subscribe(() => {
      setStateLoadingItems([...stateLoadingItems].filter(e => e !== record.id))
      actionRef.current?.reload()
    })
  }
  function onRefreshAllState() {
    console.error("lis", listDataRef.current)
    if (listDataRef.current?.length > 0) {
      $wss.hotRefreshSchedule(listDataRef.current.map(e => e.id))
    }
    
  }
  return (
    <div className='page-wrap role-page-wrap'>
      <div className="scroll-ele-wrapper">
        <ProTable
          actionRef={actionRef}
          columns={columns}
          request={(params, sorter, filter) => {
            // 表单搜索项会从 params 传入，传递给后端接口。
            console.log(params, sorter, filter);
            return firstValueFrom(
              $http.getScheduleList().pipe(
                map(res => {
                  listDataRef.current = res.data.list
                  return {
                    data: res.data.list,
                    success: true,
                  }
                })
              )
            )
          }}
          // options={false}
          toolbar={{
            search: {
              onSearch: (value) => {
                alert(value);
              },
            },
            actions: [
              <Button type="primary" onClick={() => drawerRef.current.open()}>添加</Button>,
              <Button type="primary" danger onClick={() => $wss.toggleScheduleLocked("1")}>Lock</Button>,
              <Button type="primary" onClick={() => $wss.toggleScheduleLocked("0")}>Unlock</Button>,
            ],
          }}
          rowKey="id"
          search={false}
          pagination={false}
        />
      </div>
      
      <ScheduleEditorDrawer ref={drawerRef} onFinish={() => actionRef.current?.reload()}/>
    </div>
  )
}